
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import java.util.List;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
import org.jdom.xpath.*;
import java.net.*;

@WebServlet(urlPatterns={"/imageserver/*"})
public class ImageServer extends HttpServlet {
   class FileExtensionFilter implements FileFilter {
	    private final String[] validExtensions;
	    public FileExtensionFilter(String... validExtensions) {
	        this.validExtensions = validExtensions;
	    }

	    public boolean accept(File pathname) {
	        if (pathname.isDirectory()) {
	            return true;
	        }

	        String name = pathname.getName().toLowerCase();

	        for (String ext : validExtensions) {
	            if (name.endsWith(ext)) {
	                return true;
	            }
	        }

	        return false;
	    }
	}
	
   private static final long serialVersionUID = 1L;
   private static final String _dataFilePath = "/Users/hansii/Documents/workspace/web/webtek_js/WebContent/";
   public ImageServer() {
      super();
   }
   
   @SuppressWarnings("unchecked")	
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
	   try {
           String uri = request.getRequestURI();
           uri = uri.substring(uri.indexOf("imageserver/")+11);
           Document doc = new Document();
           Element root = new Element("images");
           doc.setRootElement(root);
           
           File folder = new File(_dataFilePath+uri);  
           
           if (folder.exists()) {  
        	   File[] paths = folder.listFiles(new FileExtensionFilter(".gif", ".jpeg", ".png"));
        	   for (File path:paths) {
        		   Element img = new Element("image");
        		   img.setText(path.getName());
        		   root.addContent(img);
        	   }
        	   XMLOutputter out = new XMLOutputter();
        	   out.output(doc, response.getWriter()); 
           }
           else
               response.sendError(HttpServletResponse.SC_NOT_FOUND, "dir not found"); // 404
       }
       catch (Exception ex) {
           response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error occured: " + ex.getMessage()); // 500
       }
   }  
}
